package com.taptech.doufu.services;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.taptech.doufu.util.StringUtil;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.bean.CommentDataBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpRequestObject;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;

public class HomeMainServices extends BaseService implements HttpResponseListener {


    private static HomeMainServices instance = new HomeMainServices();
    public static final int HANDLE_TYPE_DOWN_NOVEL = 3011;
    public static final int HANDLE_TYPE_LOAD_ALBUMS = 3012;
    public static final int HANDLE_TYPE_LOAD_SECTION_NOVEL = 3004;
    public static final int HANDLE_TYPE_LOAD_NOVEL_DETAILS = 3005;
    public static final int HANDLE_TYPE_LOAD_SQUARE = 3013;
    public static final int HANDLE_TYPE_MORE_RECOMMEND_NOVEL = 3017;
    public static final int HANDLE_TYPE_REFRESH_RECOMMEND_NOVEL = 3018;

    public static final int HANDLE_TYPE_LOAD_MORE_ALBUMS = 3017;
    public static final int HANDLE_TYPE_LOAD_RANK = 3022;
    public static final int HANDLE_TYPE_NEED_PROTOCOL = 3024;

    public static final int HANDLE_TYPE_SHARE_URL = 3025;
    public static final int HANDLE_TYPE_NOVEL_PAY_ALL_URL = 3028;

    private HomeMainServices() {
    }

    public static HomeMainServices getInstance() {
        return instance;
    }


    public static void shareStatistics(final Context context,String social_type,String object_type,String id,String shareUrl) {
        HomeMainServices.getInstance().getShareUrlRequest(id, object_type,null,shareUrl);
        UGCMainService.getInstance().uploadShareScore(id,
                social_type, object_type, new HttpResponseListener() {
                    @Override
                    public void handleResponse(int handleType, HttpResponseObject response) {
                        try {
                            if (response.getStatus() == 0) {
                                UIUtil.dismissDialog();
                                CommentDataBean scrore = new CommentDataBean();
                                scrore.setJson(((JSONObject) response.getData()).getJSONObject("score_result"));
                                int commentScore = Integer.valueOf(scrore.getScore());
                                if (commentScore != 0) {
                                    UIUtil.toastMessage(context, "分享成“攻” +5豆子");
                                } else {
                                    UIUtil.toastMessage(context, "分享成“攻”"+Constant.REPLY_TODAY_FULL);
                                }
                            } else {
                                UIUtil.toastMessage(context, DiaobaoUtil.getErrorTips(response));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 广场列表
     */
    public void loadSquarelList(HttpResponseListener listener) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_SQUARE);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/square");
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }


    /**
     * 小说章节列表倒序
     *
     * @param order
     */
    public void loadNovelSectionList(HttpResponseListener listener, String id, String lastId, String order) {

        String novelOrder = "2";
        if (order != null && !TextUtil.isEmpty(order)) {
            novelOrder = order;
        }
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_SECTION_NOVEL);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/post/topic?topic_id=" + id + "&size=" + Constant.PAGE_SIZE_10 + "&last=" + lastId

                + "&order=" + novelOrder);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }


    /**
     * 小说章节列表倒序(只返回章节目录)
     */
    public void loadNovelSectionListNew(HttpResponseListener listener, String id, String order) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_SECTION_NOVEL);
        if (order != null && !order.equals("0")) {
            request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/novel/chapter_list?novel_id=" + id + "&order=desc");
        } else {
            request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/novel/chapter_list?novel_id=" + id);
        }
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    /**
     * 小说章节详情
     */
    public void loadNovelDetailsList(HttpResponseListener listener, String id, int type) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_NOVEL_DETAILS);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/post/view/" + id + "?with_ids=" + type + "&type=read");
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
        System.out.println("获取小说详情：id="+id);
    }

    public void loadPayAllNovel(HttpResponseListener listener, String novelId){
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_NOVEL_PAY_ALL_URL);
        request.setUrl(Constant.HOST_NAME_SECOND+"/index.php/full_buy/buy?object_type=18&object_id="+novelId);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    /**
     * 购买剩余章节
     * @param listener
     * @param novelId
     */
    public void loadPayVerbNovel(HttpResponseListener listener, String novelId){
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_NOVEL_PAY_ALL_URL);
        request.setUrl(Constant.HOST_NAME_SECOND+"/Novel/BatchBuy?object_type=18&novel_id="+novelId);
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        NameValuePair value;
        value = new BasicNameValuePair("novel_id", novelId);
        list.add(value);
        value = new BasicNameValuePair("object_type", "18");
        list.add(value);
        request.setListener(listener);
        request.setData(list);
        HttpUtil.sendPostRequest(request);
    }

    /**
     * 下载小说
     */
    public void loadNovel(HttpResponseListener listener, String novel_id) {
        try {
            HttpRequestObject request = new HttpRequestObject();
            request.setHandleType(HANDLE_TYPE_DOWN_NOVEL);
            List<NameValuePair> lsit = new LinkedList<NameValuePair>();
            NameValuePair value;
            value = new BasicNameValuePair("novel_id", novel_id);
            lsit.add(value);
            request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/topic/" + "offline_novel");
            request.setListener(listener);
            request.setData(lsit);
            HttpUtil.sendPostRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 专题数据and 更多数据
     */
    public void loadAlbumsList(HttpResponseListener listener, String url, String last) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_ALBUMS);
        if ((url != null) && (url.length() > 0) && (countStr(url, "?") > 1)) {
            request.setUrl(url.substring(0, url.length() - 1) + "&last=" + last + "&size=" + Constant.PAGE_SIZE_12);
        }else if((url != null) && (url.length() > 0) && (url.endsWith("?"))){
            request.setUrl(url + "last=" + last + "&size=" + Constant.PAGE_SIZE_12);
        } else {
            request.setUrl(url + "&last=" + last + "&size=" + Constant.PAGE_SIZE_12);
        }
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    /**
     * 专题数据and 更多数据
     */
    public void loadAlbumsList(HttpResponseListener listener, String url, String last ,String data) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_ALBUMS);
        String urlStr = "";
        if ((url != null) && (url.length() > 0) && (countStr(url, "?") > 1)) {
            urlStr = url.substring(0, url.length() - 1) + "&last=" + last + "&size=" + Constant.PAGE_SIZE_12;
            url = albumsSort(urlStr ,data);
            request.setUrl(url);
        } else {
            urlStr = url + "&last=" + last + "&size=" + Constant.PAGE_SIZE_12;
            url = albumsSort(urlStr ,data);
            request.setUrl(url);
        }

        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    private String albumsSort(String url ,String data){
        try {
            if(StringUtil.stringLength(data)){
                url = url+"&data = "+ URLEncoder.encode(data, "utf-8") ;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return  url;
    }
    public int countStr(String str1, String str2) {
        if (str1.indexOf(str2) == -1) {
            return 0;
        } else if (str1.indexOf(str2) != -1) {
            return 1 + countStr(str1.substring(str1.indexOf(str2) +
                    str2.length()), str2);
        } else {
            return 0;
        }
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {

    }

    public void loadMoreAlbums(String part, int size, int page, HttpResponseListener listener) {
       /* 参数：
        part: <1|2|4|5> , 热门｜小说文评｜绘画｜排行版*/
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_MORE_ALBUMS);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/home/moreRecommendedPartnAlbums" + "?part=" + part + "&size=" + Constant.SEPARATE_RETURN_DATA_NUMBER + "&begin=" + (page * Constant.SEPARATE_RETURN_DATA_NUMBER));
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }



    public void loadRankNovelDataWithUrl(HttpResponseListener listener, String url, String last) {
       /* 参数：
        part: <1|2|4|5> , 热门｜小说文评｜绘画｜排行版*/
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_LOAD_RANK);
        request.setUrl(url + "last=" + last + "&size=" + Constant.PAGE_SIZE_20);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }



    /**
     * 举报该内容
     *
     * @param reportUserId 被举报者id
     * @param object_type  举报作品类型
     * @param id           作品i，如果直接举报用户，怎id = reportUserId
     */
    public static void reportContentRequest(Context context, String reportUserId, String object_type, String id) {
        if (AccountService.getInstance().isLogin()) {
            Intent intent = new Intent(context, BrowseActivity.class);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://api.doufu.la/index.php/web/reports/index");
            stringBuilder.append("?object_type=");
            stringBuilder.append(object_type);
            stringBuilder.append("&object_id=");
            stringBuilder.append(id);
            stringBuilder.append("&object_user_id=");
            stringBuilder.append(reportUserId);
            intent.putExtra(Constant.URL, stringBuilder.toString());
            context.startActivity(intent);
        } else {
            AccountService.getInstance().jumpToLogin();
        }

    }


    /**
     * 询问服务器是否弹出协议弹窗
     *
     * @param listener
     * @param object_type
     */
    public void getProtocolRequest(HttpResponseListener listener, String object_type) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_NEED_PROTOCOL);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/member/prompt?object_type=" + object_type);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    public void getShareUrlRequest(String object_id,String object_type,HttpResponseListener listener, String originUrl) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_SHARE_URL);
        List<NameValuePair> lsit = new LinkedList<NameValuePair>();
        NameValuePair value;
        value = new BasicNameValuePair("url", originUrl);
        lsit.add(value);
        if (!TextUtils.isEmpty(object_type)) {
            value = new BasicNameValuePair("object_type", object_type);
            lsit.add(value);
        }
        if (!TextUtils.isEmpty(object_id)) {
            value = new BasicNameValuePair("object_id", object_id);
            lsit.add(value);
        }
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/sharerecords/save");
        request.setListener(listener);
        request.setData(lsit);
        HttpUtil.sendPostRequest(request);
    }

    public void getShareUrlRequest(String object_id,String object_type,HttpResponseListener listener, String originUrl, int handleType) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(handleType);
        List<NameValuePair> lsit = new LinkedList<NameValuePair>();
        NameValuePair value;
        value = new BasicNameValuePair("url", originUrl);
        lsit.add(value);
        if (!TextUtils.isEmpty(object_type)) {
            value = new BasicNameValuePair("object_type", object_type);
            lsit.add(value);
        }
        if (!TextUtils.isEmpty(object_id)) {
            value = new BasicNameValuePair("object_id", object_id);
            lsit.add(value);
        }
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/sharerecords/save");
        request.setListener(listener);
        request.setData(lsit);
        HttpUtil.sendPostRequest(request);
    }

    public static final int HANDLE_TYPE_HOMENOVELBOOKSELFMARKET = 4009;

    public void getHomeBookShelfMarket(HttpResponseListener listener) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_HOMENOVELBOOKSELFMARKET);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/entrance_item/advert");
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    public static final int HANDLE_TYPE_HOMENOVELBOOKSELF = 5001;

    public void getHomeBookShelfBanner(HttpResponseListener listener) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_HOMENOVELBOOKSELF);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/tags/mine_num");
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }


    public static final int HANDLE_TYPE_HOMENOVEL_WELFARE = 5004;

    public void getHomeNovelWelfare(String url, HttpResponseListener listener, String last) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_HOMENOVEL_WELFARE);
        request.setUrl(url + "last=" + last + "&size=" + Constant.PAGE_SIZE_20);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    public static final int HANDLE_TYPE_HOMENOVEL_NOVELCATEGORY_MORE = 5008;

    public void getHomeNovelMoreCategory(HttpResponseListener listener, String last) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_HOMENOVEL_NOVELCATEGORY_MORE);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/entrance_item/novel_more_category?last=" + last + "&size=" + Constant.PAGE_SIZE_20);
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }


    private String addSplit(String url) {
        if (url.contains("?")) {
            if (url.endsWith("&")||url.endsWith("?")) {
                return url;
            }else{
                return url + "&";
            }
        }else{
            return url + "?";
        }
    }

    public void getMoreNovel(String url, HttpResponseListener listener, String last,int page,int handlerType) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(handlerType);
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(addSplit(url));
            stringBuilder.append("last=").append(URLEncoder.encode(last, "utf-8"));
            stringBuilder.append("&page=").append(page);
            if (!url.contains("size=")) {
                stringBuilder.append("&size=").append(Constant.PAGE_SIZE_20);
            }
            request.setUrl(stringBuilder.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }

    public static final int HANDLE_TYPE_BUY_CHARTER = 7003;

    /**
     *  买
     *
     * @param sectionId   id
     */
    public void getBuyCharter(HttpResponseListener listener, String sectionId,int ticket_id) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_BUY_CHARTER);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/" + "post/buy_chapter");
        List<NameValuePair> lsit = new LinkedList<>();
        NameValuePair value;
        value = new BasicNameValuePair("object_id", sectionId);
        lsit.add(value);
        value = new BasicNameValuePair("read_ticket_id", String.valueOf(ticket_id));
        lsit.add(value);
        value = new BasicNameValuePair("object_type", "6");// 购买类型，这是购买章节的，类型为6
        lsit.add(value);
        request.setData(lsit);
        request.setListener(listener);
        HttpUtil.sendPostRequest(request);
    }

    public static final int HANDLE_TYPE_AUTO_PAY = 7004;

    /**
     *  动订阅 说
     *
     * @param novelId  说id
     */
    public void getAutoPay(HttpResponseListener listener, String novelId) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_AUTO_PAY);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/" + "post/auto_pay");
        List<NameValuePair> lsit = new LinkedList<>();
        NameValuePair value;
        value = new BasicNameValuePair("object_id", novelId);
        lsit.add(value);
        value = new BasicNameValuePair("object_type", "18");//  订阅类型，默认是18
        lsit.add(value);
        request.setData(lsit);
        request.setListener(listener);
        HttpUtil.sendPostRequest(request);
    }


    public static final int HANDLE_TYPE_BOOKSELF_POPULARIZE = 7007;

    public void getBookshelfPopularize(HttpResponseListener listener) {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(HANDLE_TYPE_BOOKSELF_POPULARIZE);
        request.setUrl(Constant.HOST_NAME_SECOND + "/index.php/ad/shelf_ad");
        request.setListener(listener);
        HttpUtil.sendGetRequest(request);
    }
}
